package model;

import java.util.*;

public class Counter {
    private static Map<String, Integer> counter = new LinkedHashMap<>();

    // 记录用户的最好成绩
    public void add(String user, Integer newCount) {
        // 更新记录
        if (counter.containsKey(user)) {
            Integer originalCount = counter.get(user);
            if (newCount < originalCount)
                counter.put(user, newCount);
        }
        // 添加记录
        else{
            counter.put(user, newCount);
        }
    }

    // 排序
    public List<Map.Entry<String, Integer>> sort(){
        List<Map.Entry<String, Integer>> list = new ArrayList<>(counter.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                int value = o1.getValue().compareTo(o2.getValue());
                if (value != 0)
                    return value;
                else
                    // 次数相同时按用户名排序
                    return o1.getKey().compareTo(o2.getKey());
            }
        });

        return list;
    }
}
